
import router, { asyncRoutes } from './router'
import store from './store'
import { getToken } from './utils/auth'
const whiteList = ['/login', '/404']
// 处理一级路由权限数据
function getFirstRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    return item.split(':')[0]
  })
  return [...new Set(newArr)]
}

// 处理二级路由权限数据
function getSecondRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}
// 根据权限标识过滤路由表
function getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes) {
  // 根据一级和二级对动态路由表做过滤 return出去过滤之后的路由表
  // 1. 根据一级路由对动态路由表做过滤
  return asyncRoutes.filter(route => {
    return firstRoutePerms.includes(route.permission)
  }).map(item => {
    // 2. 对二级路由做过滤
    return {
      ...item,
      children: item.children.filter(item => secondRoutePerms.includes(item.permission))
    }
  }).filter(route => route.path)
}

router.beforeEach(async(to, from, next) => {
  if (getToken()) {
    next()
    // 获取用户信息
    if (!store.state.user.profile.id) {
      // 获取原始权限列表
      // 1. 获取原始权限列表
      const permissions = await store.dispatch('user/getProfile')

      // 2. 处理权限数据，得到一级和二级路由权限
      const firstRoutePerms = getFirstRoutePerms(permissions)
      const secondRoutePerms = getSecondRoutePerms(permissions)
      // 3. 根据权限过滤路由表
      const isAdmin = permissions.some(permission => permission === '*:*:*')
      let filterRoutes = []
      if (isAdmin) {
        filterRoutes = asyncRoutes
      } else {
        filterRoutes = getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes)
      }
      console.log('权限', permissions)
      console.log('筛选后的路由表', filterRoutes)
      // 4. 动态添加过滤后的路由
      router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
      // router.addRoute([...filterRoutes])
      // 5. 将过滤后的路由存储到 Vuex，便于后续在S菜单中使用
      store.commit('menu/setMenuList', filterRoutes)
      // 保证路由表已经添加，重新跳转当前路由
      next(to.path)
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
